package validator

import (
	"errors"
	"reflect"
	"gopkg.in/go-playground/validator.v9"
	ut "github.com/go-playground/universal-translator"
	zh_t "github.com/go-playground/validator/translations/zh"
	"github.com/go-playground/locales/zh"
)

type defaultValidator struct {
	validate	*validator.Validate
	trans			ut.Translator
}

var StructValidator = &defaultValidator{}

func init() {
	chinese := zh.New()
	uni := ut.New(chinese, chinese)
	trans, _ := uni.GetTranslator("zh")
	StructValidator.trans = trans

	StructValidator.validate = validator.New()
	StructValidator.validate.SetTagName("binding")
	_ = zh_t.RegisterDefaultTranslations(StructValidator.validate, trans)
	// validate.RegisterTranslation("requred", )
}

func (v *defaultValidator) ValidateStruct(obj interface{}) error {
	if kindOfData(obj) == reflect.Struct {
		if err := v.validate.Struct(obj); err != nil {
			return v.initErros(err)
		}
	}
	return nil
}

func kindOfData(data interface{}) reflect.Kind {
	value := reflect.ValueOf(data)
	valueType := value.Kind()
	if valueType == reflect.Ptr {
		valueType = value.Elem().Kind()
	}
	return valueType
}

func (v *defaultValidator) initErros(err error) error {
	errs := err.(validator.ValidationErrors)
	// buffer := bytes.NewBufferString("")
	// for _, e := range errs {
	// 	buffer.WriteString(e.Translate(v.trans))
	// }
	return errors.New(errs[0].Translate(v.trans))
}